package com.visual.open.anpr.exps;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;

import java.util.Base64;

public class CameraCapture {

//    static {
//        // 加载OpenCV本地库
//        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//
//    }
    static{ nu.pattern.OpenCV.loadShared(); }
    public static void main(String[] args) {
        // 打开摄像头
        VideoCapture capture = new VideoCapture(0);
        if (!capture.isOpened()) {
            System.out.println("无法打开摄像头");
            return;
        }

        // 设置摄像头分辨率（可选）
        capture.set(Videoio.CAP_PROP_FRAME_WIDTH, 640);
        capture.set(Videoio.CAP_PROP_FRAME_HEIGHT, 480);

        Mat frame = new Mat();
        while (true) {
            // 读取一帧图像
            capture.read(frame);

            // 检查是否成功读取图像
            if (!frame.empty()) {
                // 将图像保存为文件
                Imgcodecs.imwrite("capture1.jpg", frame);

                // 将图像转换为Base64编码
                String base64Image = matToBase64(frame);
                System.out.println("Base64 Image: " + base64Image);

                break; // 捕获一帧后退出循环
            }
        }

        // 释放摄像头
        capture.release();
    }

    // 将Mat对象转换为Base64编码的字符串
    private static String matToBase64(Mat mat) {
        MatOfByte matOfByte = new MatOfByte();
        Imgcodecs.imencode(".jpg", mat, matOfByte);
        byte[] byteArray = matOfByte.toArray();
        return Base64.getEncoder().encodeToString(byteArray);
    }
}